<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Msg as MsgModel;
use think\Config;
use think\Hook;
use think\Log;

/**
 * 消息接口
 */
class Msg extends Api
{
    protected $noNeedLogin = ['send'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /**
     * 发送消息
     * @ApiMethod (POST)
     * @ApiParams (name="yourname", type="string", required=true, description="姓名")
     * @ApiParams (name="youremail", type="string", required=true, description="邮箱")
     * @ApiParams (name="theme", type="string", required=true, description="主题")
     * @ApiParams (name="yourmessage", type="string", required=false, description="消息内容")
     */
    public function send()
    {
        try {
            // 获取请求参数
            $data = $this->request->post();
            
            // 手动验证必填参数
            if (empty($data['yourname'])) {
                $this->error('姓名不能为空');
            }
            if (empty($data['youremail'])) {
                $this->error('邮箱不能为空');
            }
            if (empty($data['theme'])) {
                $this->error('主题不能为空');
            }
            
            // 验证邮箱格式
            if (!filter_var($data['youremail'], FILTER_VALIDATE_EMAIL)) {
                $this->error('邮箱格式不正确');
            }
            
            // 准备消息数据
            $msgData = [
                'yourname' => $data['yourname'],
                'youremail' => $data['youremail'],
                'theme' => $data['theme'],
                'yourmessage' => isset($data['yourmessage']) ? $data['yourmessage'] : ''
            ];
            
            // 记录调试信息
            \think\Log::info('消息数据: ' . json_encode($msgData));
            
            // 检查数据库连接
            try {
                $db = \think\Db::name('msg');
                \think\Log::info('数据库连接成功');
            } catch (\Exception $e) {
                \think\Log::error('数据库连接失败: ' . $e->getMessage());
                $this->error('数据库连接失败');
            }
            
            // 检查表是否存在
            try {
                $tableExists = $db->query('SHOW TABLES LIKE "msg"');
                \think\Log::info('表检查结果: ' . json_encode($tableExists));
            } catch (\Exception $e) {
                \think\Log::error('表检查失败: ' . $e->getMessage());
                $this->error('表检查失败');
            }
            
            // 插入数据
            $result = $db->insert($msgData);
            \think\Log::info('插入结果: ' . ($result ? '成功' : '失败'));
            
            if ($result) {
                $id = $db->getLastInsID();
                
                // 直接返回JSON，绕过success方法
                $result = [
                    'code' => 1,
                    'msg' => '消息发送成功',
                    'time' => time(),
                    'data' => [
                        'id' => (int)$id,
                        'yourname' => (string)$data['yourname'],
                        'youremail' => (string)$data['youremail'],
                        'theme' => (string)$data['theme'],
                        'yourmessage' => isset($data['yourmessage']) ? (string)$data['yourmessage'] : ''
                    ]
                ];
                
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            } else {
                $this->error('消息发送失败');
            }
            
        } catch (\Exception $e) {
            // 记录错误日志
            \think\Log::error('发送消息失败: ' . $e->getMessage());
            \think\Log::error('错误详情: ' . $e->getTraceAsString());
            
            $this->error('消息发送失败');
        }
    }
}
